package com.stable.actor.remotedemo;


import com.alibaba.fastjson.JSON;
import com.stable.actor.core.ActorRef;
import com.stable.actor.core.StableActor;
import com.stable.actor.network.ServiceResponse;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.function.Consumer;

/**
 * 订单服务Actor - 协调远程调用
 */
@Slf4j
public class OrderServiceActor extends StableActor {
    private ActorRef paymentService;
    private ActorRef inventoryService;
    private ActorRef notificationService;

    public OrderServiceActor() {

    }
    // 用于跟踪订单状态
    private int processedOrders = 0;
    private int successfulOrders = 0;

    public void setRemoteServices(ActorRef paymentService, ActorRef inventoryService, ActorRef notificationService) {
        this.paymentService = paymentService;
        this.inventoryService = inventoryService;
        this.notificationService = notificationService;
        log.info("🔗 订单服务已设置远程服务引用");
    }

    @Override
    protected void setupMessageHandlers() {
        // 直接操作 messageHandlers，避免覆盖
        messageHandlers.put(CreateOrderCommand.class, (Consumer<Object>) msg -> {
            if (msg instanceof CreateOrderCommand) {
                handleCreateOrder((CreateOrderCommand) msg);
            }
        });
        messageHandlers.put(ServiceResponse.class, (Consumer<Object>) msg -> {
            if (msg instanceof ServiceResponse) {
                handleServiceResponse((ServiceResponse) msg);
            }
        });
        messageHandlers.put(Map.class, (Consumer<Object>) msg -> {
            if (msg instanceof Map) {
                handleMapMessage((Map<String, Object>) msg);
            }
        });

        // 对于会冲突的类型，谨慎处理
        if (!messageHandlers.containsKey(String.class)) {
            messageHandlers.put(String.class, (Consumer<Object>) msg -> {
                if (msg instanceof String) {
                    handleStringMessage((String) msg);
                }
            });
        }

        log.info("✅ 订单服务消息处理器设置完成，共 {} 个处理器", messageHandlers.size());
    }

    /**
     * 处理可能的 LinkedHashMap 消息（JSON 反序列化后的结果）
     */
    @SuppressWarnings("unchecked")
    private void handleMapMessage(Map<String, Object> map) {
        log.info("🔄 收到 Map 类型消息，尝试转换为 CreateOrderCommand: {}", map.keySet());

        try {
            // 检查是否是 CreateOrderCommand
            if (map.containsKey("order")) {
                Object orderObj = map.get("order");
                if (orderObj instanceof Map) {
                    Map<String, Object> orderMap = (Map<String, Object>) orderObj;
                    Order order = mapToOrder(orderMap);
                    CreateOrderCommand command = new CreateOrderCommand(order);
                    handleCreateOrder(command);
                    return;
                }
            }

            log.warn("⚠️ 无法识别的 Map 消息结构: {}", map);

        } catch (Exception e) {
            log.error("❌ 处理 Map 消息失败", e);
        }
    }

    /**
     * 将 Map 转换为 Order 对象
     */
    private Order mapToOrder(Map<String, Object> map) {
        String mapJson = JSON.toJSONString(map);
        Order order = JSON.parseObject(mapJson, Order.class);
        return order;
    }
    private <String> void handleStringMessage(String t) {
        log.info("📨 订单服务收到字符串消息: " + t);
    }

    @Override
    public void handleMessage(Object message) {
        log.info("📨 订单服务收到消息: " + message);

        if (message instanceof CreateOrderCommand) {
            handleCreateOrder((CreateOrderCommand) message);
        } else if (message instanceof String) {
            handleServiceResponse((String) message);
        } else if (message instanceof ServiceResponse) {
            handleServiceResponse((ServiceResponse) message);
        } else {
            log.info("❓ 未知消息类型: " + message.getClass().getSimpleName());
        }
    }

    private void handleCreateOrder(CreateOrderCommand command) {
        Order order = command.getOrder();
        processedOrders++;

        log.info("\n🛒 开始处理订单: " + order.getOrderId());
        log.info("   商品: " + order.getProductName() + ", 数量: " + order.getQuantity() + ", 金额: " + order.getAmount());

        // 1. 检查库存
        log.info("📦 发送库存检查请求...");
        InventoryCheckRequest inventoryRequest = new InventoryCheckRequest(
                order.getOrderId(), order.getProductName(), order.getQuantity());
        inventoryService.tell(inventoryRequest, getSelf());

        // 2. 处理支付（在库存检查成功后处理）
        // 注意：这里简化了流程，实际应该等待库存检查响应后再支付
        log.info("💳 发送支付请求...");
        PaymentRequest paymentRequest = new PaymentRequest(
                order.getOrderId(), order.getUserId(), order.getAmount());
        paymentService.tell(paymentRequest, getSelf());

        // 3. 发送通知
        log.info("📢 发送订单创建通知...");
        String notificationMsg = String.format("订单 %s 已创建，金额: %.2f元", order.getOrderId(), order.getAmount());
        NotificationRequest notificationRequest = new NotificationRequest(order.getUserId(), notificationMsg);
        notificationService.tell(notificationRequest, getSelf());

        log.info("✅ 订单处理流程已启动");
    }

    private void handleServiceResponse(String response) {
        log.info("📨 收到服务响应: " + response);

        // 根据响应内容处理
        if (response.contains("库存") || response.toLowerCase().contains("inventory")) {
            log.info("✅ 库存服务响应: " + response);
        } else if (response.contains("支付") || response.contains("payment")) {
            log.info("✅ 支付服务响应: " + response);
            if (response.contains("成功")) {
                successfulOrders++;
            }
        } else if (response.contains("通知") || response.contains("notification")) {
            log.info("✅ 通知服务响应: " + response);
        }
    }

    private void handleServiceResponse(ServiceResponse response) {
        log.info("📨 收到结构化响应: " + response.getServiceType() + " - " + response.getMessage());

        switch (response.getServiceType()) {
            case "inventory":
                if (response.isSuccess()) {
                    log.info("✅ 库存检查通过: " + response.getMessage());
                } else {
                    log.info("❌ 库存不足: " + response.getMessage());
                }
                break;

            case "payment":
                if (response.isSuccess()) {
                    log.info("🎉 支付成功: " + response.getMessage());
                    successfulOrders++;
                } else {
                    log.info("💸 支付失败: " + response.getMessage());
                }
                break;

            case "notification":
                log.info("📬 通知状态: " + response.getMessage());
                break;
        }

        // 打印统计信息
        log.info("📊 订单统计: 已处理 " + processedOrders + " 个订单, 成功 " + successfulOrders + " 个");
    }

    @Override
    protected void preStart() {
        log.info("🚀 订单服务启动完成");
    }

    @Override
    protected void postStop() {
        log.info("📊 订单服务停止，最终统计:");
        log.info("   总处理订单: " + processedOrders);
        log.info("   成功订单: " + successfulOrders);
        log.info("   成功率: " + (processedOrders > 0 ? (successfulOrders * 100.0 / processedOrders) : 0) + "%");
    }
}
